<template>
  <div class="login-container">
    <div class="login-content">
      <div class="login-card">
        <div class="title-container">
          <h1 class="logo-title">高校志愿服务</h1>
          <p class="subtitle">温暖你我，志愿同行</p>
        </div>

        <el-form
            ref="loginFormRef"
            :model="loginForm"
            :rules="loginRules"
            class="login-form"
            autocomplete="on"
            label-position="left"
        >
          <el-tabs v-model="activeTab" @tab-click="handleTabClick" class="login-tabs">
            <el-tab-pane label="登录" name="login">
              <el-form-item prop="name">
                <el-input
                    v-model="loginForm.name"
                    placeholder="请输入学号"
                    type="text"
                    tabindex="1"
                    :prefix-icon="User"
                    class="custom-input"
                />
              </el-form-item>

              <el-form-item prop="password">
                <el-input
                    v-model="loginForm.password"
                    :type="passwordVisible ? 'text' : 'password'"
                    placeholder="密码"
                    tabindex="2"
                    :prefix-icon="Lock"
                    show-password
                    class="custom-input"
                />
              </el-form-item>

              <el-form-item label="" prop="role">
                <el-select v-model="loginForm.role" placeholder="请选择角色">
                  <el-option label="管理员" value="admin" />
                  <el-option label="负责人" value="leader" />
                  <el-option label="志愿者" value="volunteer" />
                </el-select>
              </el-form-item>


              <el-form-item prop="rememberMe" class="remember-me">
                <el-checkbox v-model="loginForm.rememberMe">记住我</el-checkbox>
                <el-button type="text" class="forget-pwd" @click="handleForgetPassword">忘记密码?</el-button>
              </el-form-item>

              <el-button :loading="loading" type="primary" class="login-button" @click="handleLogin">
                {{ loading ? '登录中...' : '登录' }}
              </el-button>
            </el-tab-pane>

            <el-tab-pane label="注册" name="register">
              <el-form-item>
                <el-input
                    v-model="registerForm.name"
                    placeholder="用户名"
                    type="text"
                    tabindex="1"
                    autocomplete="off"
                    :prefix-icon="User"
                    class="custom-input"
                />
              </el-form-item>

              <el-form-item>
                <el-input
                    v-model="registerForm.studentId"
                    placeholder="学号"
                    type="text"
                    tabindex="1"
                    autocomplete="off"
                    :prefix-icon="User"
                    class="custom-input"
                />
              </el-form-item>

              <el-form-item>
                <el-input
                    v-model="registerForm.password"
                    :type="passwordVisible ? 'text' : 'password'"
                    placeholder="密码"
                    tabindex="2"
                    autocomplete="off"
                    :prefix-icon="Lock"
                    show-password
                    class="custom-input"
                />
              </el-form-item>

              <el-form-item>
                <el-input
                    v-model="registerForm.email"
                    placeholder="邮箱"
                    type="email"
                    tabindex="4"
                    autocomplete="off"
                    :prefix-icon="Message"
                    class="custom-input"
                />
              </el-form-item>

              <el-form-item>
                <el-input
                    v-model="registerForm.phone"
                    placeholder="手机号"
                    type="text"
                    tabindex="5"
                    autocomplete="off"
                    :prefix-icon="Phone"
                    class="custom-input"
                />
              </el-form-item>

              <el-button :loading="registerLoading" type="primary" class="login-button" @click="handleRegister">
                {{ registerLoading ? '注册中...' : '注册' }}
              </el-button>
            </el-tab-pane>
          </el-tabs>
        </el-form>

        <div class="login-footer">
          <p>© 2023 高校志愿服务管理系统 - 让志愿服务更美好</p>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import {ref, reactive, onMounted} from 'vue'
import {useRouter} from 'vue-router'
import {useUserStore} from '@/stores/user'
import {ElMessage} from 'element-plus'
import {User, Lock, Message, Phone} from '@element-plus/icons-vue'
import {login} from '@/api/user'

const router = useRouter()
const userStore = useUserStore()
const loginFormRef = ref(null)

// 登录表单数据
const loginForm = reactive({
  name: '',
  password: '',
  rememberMe: false,
  role:''
})

// 注册表单数据
const registerForm = reactive({
  name: '',
  studentId: '',
  password: '',
  confirmPassword: '',
  email: '',
  phone: ''
})

// 表单验证规则
const loginRules = {
  name: [
    {required: true, message: '请输入用户名', trigger: 'blur'}
  ],
  password: [
    {required: true, message: '请输入密码', trigger: 'blur'}
  ]
}

// 当前激活的选项卡
const activeTab = ref('login')
// 密码可见性
const passwordVisible = ref(false)
// 登录加载状态
const loading = ref(false)
// 注册加载状态
const registerLoading = ref(false)

// 处理选项卡切换
const handleTabClick = (tab) => {
  activeTab.value = tab.props.name
}

// 处理登录
const handleLogin = async () => {
  loading.value = true
  try {
    if (!loginForm.name || !loginForm.password || !loginForm.role) {
      ElMessage.warning('请输入用户名、密码和角色')
      loading.value = false
      return
    }
    await userStore.login({
      name: loginForm.name,
      password: loginForm.password,
      role: loginForm.role
    })
    // 登录成功后根据角色跳转
    if (loginForm.role === 'admin' || loginForm.role === 'leader') {
      router.replace('/admin/dashboard')
      // todo 获取用户菜单

    } else {
      router.replace('/front/home')
    }
  } catch (e) {
    // ...错误处理
  } finally {
    loading.value = false
  }
}

// 处理注册
const handleRegister = async () => {
  registerLoading.value = true
  try {
    // 校验输入
    if (!registerForm.name || !registerForm.password || !registerForm.studentId) {
      ElMessage.warning('用户名、密码和学号不能为空')
      registerLoading.value = false
      return
    }

    if (registerForm.password.length < 6) {
      ElMessage.warning('密码长度不能小于6位')
      registerLoading.value = false
      return
    }

    // 构建注册请求数据
    const userInfo = {
      name: registerForm.name,
      password: registerForm.password,
      email: registerForm.email || undefined,
      phone: registerForm.phone || undefined,
      studentId: registerForm.studentId
    }

    console.log('开始注册，请求数据:', JSON.stringify(userInfo))
    await userStore.register(userInfo)

    ElMessage({
      message: '注册成功，请登录',
      type: 'success',
      duration: 2000
    })

    // 重置表单并切换到登录选项卡
    registerForm.name = ''
    registerForm.password = ''
    registerForm.confirmPassword = ''
    registerForm.email = ''
    registerForm.phone = ''
    registerForm.studentId = ''
    activeTab.value = 'login'
  } catch (error) {
    console.error('注册失败:', error)
    ElMessage({
      message: '注册失败，' + (error.message || '请稍后重试'),
      type: 'error',
      duration: 2000
    })
  } finally {
    registerLoading.value = false
  }
}

// 处理忘记密码
const handleForgetPassword = () => {
  ElMessage({
    message: '请联系管理员重置密码',
    type: 'info',
    duration: 3000
  })
}

onMounted(() => {
  // 如果有token，且token仍然有效，直接跳转到首页
  if (userStore.token) {
    router.push('/')
  }
})
</script>

<style lang="scss" scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  width: 100%;
  background: url('https://picsum.photos/id/1050/1920/1080') center center no-repeat;
  background-size: cover;
  position: relative;

  &::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.4);
    backdrop-filter: blur(5px);
  }

  .login-content {
    position: relative;
    z-index: 1;
    max-width: 90%;
    width: 480px;
  }

  .login-card {
    background: rgba(255, 255, 255, 0.9);
    border-radius: 12px;
    box-shadow: 0 15px 35px rgba(0, 0, 0, 0.2);
    padding: 40px;
    overflow: hidden;
    backdrop-filter: blur(10px);

    .title-container {
      text-align: center;
      margin-bottom: 30px;

      .logo-title {
        font-size: 28px;
        font-weight: bold;
        color: #409EFF;
        margin-bottom: 8px;
      }

      .subtitle {
        font-size: 16px;
        color: #606266;
        margin: 0;
      }
    }

    .login-form {
      width: 100%;

      .custom-input {
        background: rgba(255, 255, 255, 0.8);
        border-radius: 8px;

        :deep(.el-input__wrapper) {
          padding: 12px 15px;
          box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
        }
      }

      .remember-me {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 20px;

        .forget-pwd {
          color: #409EFF;
          padding: 0;
        }
      }

      .login-button {
        width: 100%;
        height: 48px;
        border-radius: 8px;
        font-size: 16px;
        font-weight: 500;
        margin-top: 10px;
        background: linear-gradient(135deg, #409EFF, #4069FF);
        border: none;

        &:hover {
          background: linear-gradient(135deg, #4069FF, #409EFF);
        }
      }
    }

    .login-tabs {
      :deep(.el-tabs__header) {
        margin-bottom: 25px;
      }

      :deep(.el-tabs__item) {
        font-size: 18px;
        color: #606266;

        &.is-active {
          color: #409EFF;
          font-weight: bold;
        }
      }

      :deep(.el-tabs__active-bar) {
        background-color: #409EFF;
        height: 3px;
        border-radius: 3px;
      }
    }

    .login-footer {
      text-align: center;
      margin-top: 30px;
      color: #909399;
      font-size: 14px;
    }
  }
}

@media (max-width: 576px) {
  .login-container {
    .login-content {
      width: 95%;
    }

    .login-card {
      padding: 25px;

      .title-container {
        .logo-title {
          font-size: 24px;
        }

        .subtitle {
          font-size: 14px;
        }
      }
    }
  }
}
</style>
